Web development and Tech news Blog site. WEBISFREE.com

HOME > python

[Python] How to use cookies in Flask, cookie

Last Modified : 04 Mar, 2023 / Created : 04 Mar, 2023
714
View Count

I would like to briefly learn about how to use cookies in Flask.



# Using cookies in Flask.

Recently, while applying the jwt (Json Web Token) method in Python, there was a need to load and use cookie values. In this case, let's briefly look at the methods and examples to access cookie values. First of all, to obtain a cookie in Flask, you need to access Flask's request as shown below.
from flask import request

In fact, with a request, you can access various information including cookies sent to the server. This means that you can obtain not only cookies, but also URLs, parameters, files, and other information. To retrieve the cookie value, you can use the get() function of the cookies attribute in the request object as shown below. The syntax is simple as follows.

request.cookies.get('cookie_name')

The get() function is a simple function that retrieves and returns the value of a specific named cookie. Let's write an example of retrieving the value of a cookie named "tkn" that has been passed from the client to the server.


! Example of using Flask token value

The function getToken() is an example code to retrieve cookie value. If there is a token named tkn, this code is written to retrieve it from the Flask server.
from flask import request

def getToken():
  try:
    token = request.cookies.get('tkn')
    tokenDecode = jwt.decode(token, SECRET_KEY, algorithms=['HS267'])
    ....
  except:
    ## Error
    ...

In the above example, the try-except statement was used for error and exception handling. Looking at the code briefly, it is as follows:

- Import flask's request to get the token value.
- Use request.cookies.get() to store the token value in the variable token.
- (Note) Decode and use variable token using the jwt module.
- (Note) Use try-catch to handle exceptions.


We have briefly looked at how to retrieve token values in Flask up to this point. Note that the reason we used the try-except syntax above was to handle errors that may occur during the jwt.decode() process. This portion was added to handle errors. However, it is not always necessary to use try-except to simply obtain token information.

Previous

How to convert lower case to upper case in Python